package elsa.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

public class Method {

    //文件转移
    public void copyFile(String oldPath, String newPath) {
        String classPath = this.getClass().getClassLoader().getResource("").getPath();
        String path = classPath.substring(0,classPath.indexOf("WEB-INF"))+"file/";
        path=path.replaceAll("%20"," ");
        oldPath = path+oldPath;
        newPath = path+newPath;
        File oldfile = new File(oldPath);
        File newfile = new File(newPath);
        System.out.println(oldPath+"   "+newPath);
        try {
//            int bytesum = 0;
            int byteread = 0;
            if (oldfile.exists()) { //文件存在时
//                // 检测是否存在目录
//                if(newfile.getParentFile().exists()){
//                    File parentdest = new File(newfile.getParentFile().getAbsolutePath());
//                    File[] files = parentdest.listFiles();
//                    for(int i =0; i<files.length; i++){
//                        files[i].delete();
//                    }
//                }
                if(!newfile.getParentFile().exists()){
                    newfile.getParentFile().mkdirs();
                }
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                while ( (byteread = inStream.read(buffer)) != -1) {
//                    bytesum += byteread; //字节数 文件大小
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
                fs.close();
                oldfile.delete();
            }
        }
        catch (Exception e) {
            System.out.println("文件操作错误!");
            e.printStackTrace();
        }
    }

    //文件删除
    public void deleteFile(String path){
        String classPath = this.getClass().getClassLoader().getResource("").getPath();
        String thepath = classPath.substring(0,classPath.indexOf("WEB-INF"))+"file/";
        path = thepath+path;
        path=path.replaceAll("%20"," ");
        System.out.println(path);
        try{
            File file = new File(path);
            if(file.exists()){
                file.delete();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //文件夹删除
    public boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list(); //递归删除目录中的子目录下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }
}
